<template>
  <div class="main-layout">
    <CommonHeader />
    <FloatingSidebar />

    <div class="content-center-wrapper">
      <div class="history-view">
        <div class="history-header">
          <h2 class="page-title">浏览历史</h2>
          <el-button type="danger" @click="clearHistory" :disabled="history.length === 0">
            清空历史记录
          </el-button>
        </div>
        
        <div class="history-content" v-loading="loading">
          <el-empty v-if="!loading && history.length === 0" description="暂无浏览记录" />
          <div v-else class="history-list">
            <el-card v-for="item in history" :key="item.id" class="history-item">
              <div class="history-item-content">
                <img :src="item.image" class="product-image" @click="viewProduct(item.productId)" />
                <div class="product-info" @click="viewProduct(item.productId)">
                  <h3 class="product-title">{{ item.title }}</h3>
                  <p class="product-price">¥{{ item.price }}</p>
                  <p class="browse-time">浏览时间：{{ formatTime(item.browseTime) }}</p>
                </div>
                <div class="history-actions">
                  <el-button type="primary" @click="addToCart(item.productId)">加入购物车</el-button>
                  <el-button type="danger" @click="removeHistory(item.id)">删除</el-button>
                </div>
              </div>
            </el-card>
          </div>
        </div>

        <div class="pagination" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <CommonFooter />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import CommonHeader from '@/components/CommonHeader.vue'
import CommonFooter from '@/components/CommonFooter.vue'
import FloatingSidebar from '@/components/FloatingSidebar.vue'

const router = useRouter()
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const history = ref([])

const loadHistory = async () => {
  loading.value = true
  try {
    // TODO: 调用获取历史记录 API
    // const response = await getHistory({
    //   page: currentPage.value,
    //   pageSize: pageSize.value
    // })
    // history.value = response.data
    // total.value = response.total

    // 模拟数据
    history.value = [
      {
        id: 1,
        productId: 1,
        title: '浏览过的商品1',
        price: 99.99,
        image: 'https://via.placeholder.com/200',
        browseTime: new Date().toISOString()
      },
      // ... 更多记录
    ]
    total.value = 100
  } catch (error) {
    ElMessage.error('获取历史记录失败')
  } finally {
    loading.value = false
  }
}

const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

const viewProduct = (productId) => {
  router.push(`/home/product/${productId}`)
}

const addToCart = async (productId) => {
  try {
    // TODO: 调用加入购物车 API
    // await addToCart(productId)
    ElMessage.success('已加入购物车')
  } catch (error) {
    ElMessage.error('加入购物车失败')
  }
}

const removeHistory = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条浏览记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // TODO: 调用删除历史记录 API
    // await removeHistoryItem(id)
    
    ElMessage.success('删除成功')
    loadHistory()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

const clearHistory = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有浏览记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // TODO: 调用清空历史记录 API
    // await clearHistory()
    
    ElMessage.success('已清空历史记录')
    loadHistory()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败，请稍后重试')
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadHistory()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadHistory()
}

onMounted(() => {
  loadHistory()
})
</script>

<style scoped>
.main-layout {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.content-center-wrapper {
  flex-grow: 1;
  display: flex;
  justify-content: center;
}

.history-view {
  max-width: 1200px;
  padding: 20px;
  width: 100%;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.history-item {
  transition: transform 0.3s ease;
}

.history-item:hover {
  transform: translateX(5px);
}

.history-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  cursor: pointer;
}

.product-info {
  flex: 1;
  cursor: pointer;
}

.product-title {
  margin: 0;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin: 10px 0;
}

.browse-time {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.history-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 暗黑模式样式 */
:root.dark .page-title {
  color: #ffffff;
}

:root.dark .history-item {
  background-color: #2b2b2b;
  border-color: #3a3a3a;
}

:root.dark .product-title {
  color: #ffffff;
}

:root.dark .browse-time {
  color: #909399;
}
</style> 